<template>
  <div class="exam-card" :class="cardClass" @click="handleCardClick">
    <!-- 考试状态标识 -->
    <div class="exam-status" :class="`status-${exam.status}`">
      <el-icon><component :is="getStatusIcon(exam.status)" /></el-icon>
      <span>{{ getStatusText(exam.status) }}</span>
    </div>
    
    <!-- 考试信息 -->
    <div class="exam-info">
      <!-- 考试标题 -->
      <h3 class="exam-title" :title="exam.title">
        {{ exam.title }}
      </h3>
      
      <!-- 考试描述 -->
      <p class="exam-description" v-if="exam.description">
        {{ exam.description }}
      </p>
      
      <!-- 考试标签 -->
      <div class="exam-tags" v-if="exam.tags && exam.tags.length > 0">
        <el-tag 
          v-for="tag in exam.tags.slice(0, 3)" 
          :key="tag"
          size="small"
          type="info"
          class="exam-tag"
        >
          {{ tag }}
        </el-tag>
        <span v-if="exam.tags.length > 3" class="more-tags">
          +{{ exam.tags.length - 3 }}
        </span>
      </div>
      
      <!-- 考试统计信息 -->
      <div class="exam-stats">
        <div class="stat-item" v-if="exam.questionCount">
          <el-icon><Document /></el-icon>
          <span>{{ exam.questionCount }}题</span>
        </div>
        <div class="stat-item" v-if="exam.duration">
          <el-icon><Clock /></el-icon>
          <span>{{ formatDuration(exam.duration) }}</span>
        </div>
        <div class="stat-item" v-if="exam.participantCount">
          <el-icon><User /></el-icon>
          <span>{{ formatNumber(exam.participantCount) }}人参与</span>
        </div>
        <div class="stat-item" v-if="exam.difficulty">
          <el-icon><TrendCharts /></el-icon>
          <span>{{ getDifficultyText(exam.difficulty) }}</span>
        </div>
      </div>
      
      <!-- 考试时间信息 -->
      <div class="exam-time">
        <div class="time-item" v-if="exam.startTime">
          <el-icon><Calendar /></el-icon>
          <span>开始时间：{{ formatDateTime(exam.startTime) }}</span>
        </div>
        <div class="time-item" v-if="exam.endTime">
          <el-icon><Calendar /></el-icon>
          <span>结束时间：{{ formatDateTime(exam.endTime) }}</span>
        </div>
        <div class="time-item" v-if="exam.remainingTime && exam.status === 'ongoing'">
          <el-icon><Timer /></el-icon>
          <span class="remaining-time">剩余时间：{{ formatRemainingTime(exam.remainingTime) }}</span>
        </div>
      </div>
      
      <!-- 考试成绩 -->
      <div class="exam-score" v-if="exam.score !== undefined && exam.status === 'completed'">
        <div class="score-info">
          <span class="score-label">考试成绩：</span>
          <span class="score-value" :class="getScoreClass(exam.score)">
            {{ exam.score }}分
          </span>
          <span class="score-status" :class="getScoreClass(exam.score)">
            ({{ getScoreStatus(exam.score) }})
          </span>
        </div>
        <el-progress 
          :percentage="exam.score" 
          :color="getScoreColor(exam.score)"
          :stroke-width="6"
          :show-text="false"
        />
      </div>
      
      <!-- 考试进度 -->
      <div class="exam-progress" v-if="exam.progress !== undefined && exam.status === 'in_progress'">
        <div class="progress-info">
          <span class="progress-label">答题进度：</span>
          <span class="progress-value">{{ exam.progress }}%</span>
        </div>
        <el-progress 
          :percentage="exam.progress" 
          :stroke-width="6"
          :show-text="false"
        />
      </div>
      
      <!-- 操作按钮 -->
      <div class="exam-actions">
        <el-button 
          v-if="exam.status === 'upcoming'"
          type="primary" 
          size="small" 
          @click.stop="handleEnroll"
          :loading="enrollLoading"
          :disabled="!canEnroll"
        >
          {{ isEnrolled ? '已报名' : '立即报名' }}
        </el-button>
        
        <el-button 
          v-if="exam.status === 'ongoing' && isEnrolled"
          type="success" 
          size="small" 
          @click.stop="handleStartExam"
        >
          {{ exam.progress > 0 ? '继续考试' : '开始考试' }}
        </el-button>
        
        <el-button 
          v-if="exam.status === 'completed' && exam.score !== undefined"
          type="info" 
          size="small" 
          @click.stop="handleViewResult"
        >
          查看成绩
        </el-button>
        
        <el-button 
          size="small" 
          @click.stop="handleViewDetails"
        >
          查看详情
        </el-button>
        
        <!-- 收藏按钮 -->
        <el-button 
          circle 
          size="small" 
          :type="isFavorited ? 'danger' : 'info'"
          :icon="isFavorited ? StarFilled : Star"
          @click.stop="handleFavorite"
          class="favorite-btn"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Document,
  Clock,
  User,
  TrendCharts,
  Calendar,
  Timer,
  Star,
  StarFilled,
  CircleCheck,
  Clock as ClockIcon,
  Warning,
  CircleClose
} from '@element-plus/icons-vue'
import { useExamStore } from '@/stores/exam'
import { useUserStore } from '@/stores/user'
import { formatDuration, formatNumber, formatDateTime } from '@/utils'

// Props
const props = defineProps({
  // 考试数据
  exam: {
    type: Object,
    required: true
  },
  // 卡片大小
  size: {
    type: String,
    default: 'medium',
    validator: (value) => ['small', 'medium', 'large'].includes(value)
  },
  // 是否可点击
  clickable: {
    type: Boolean,
    default: true
  },
  // 自定义类名
  customClass: {
    type: String,
    default: ''
  }
})

// Emits
const emit = defineEmits(['click', 'enroll', 'start', 'favorite'])

const router = useRouter()
const examStore = useExamStore()
const userStore = useUserStore()

// 响应式数据
const enrollLoading = ref(false)

// 计算属性
const cardClass = computed(() => ({
  [`exam-card--${props.size}`]: true,
  'exam-card--clickable': props.clickable,
  [props.customClass]: props.customClass
}))

const isFavorited = computed(() => {
  // 这里应该从 store 中获取收藏状态
  return false
})

const isEnrolled = computed(() => {
  return examStore.myExams.some(exam => exam.id === props.exam.id)
})

const canEnroll = computed(() => {
  const now = new Date()
  const startTime = new Date(props.exam.startTime)
  return now < startTime
})

// 方法
const handleCardClick = () => {
  if (props.clickable) {
    emit('click', props.exam)
    router.push(`/exams/${props.exam.id}`)
  }
}

const handleEnroll = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  if (isEnrolled.value) {
    return
  }
  
  try {
    enrollLoading.value = true
    // 这里应该调用报名 API
    // await examStore.enrollExam(props.exam.id)
    ElMessage.success('报名成功')
    emit('enroll', props.exam)
  } catch (error) {
    console.error('报名失败:', error)
    ElMessage.error('报名失败，请重试')
  } finally {
    enrollLoading.value = false
  }
}

const handleStartExam = () => {
  emit('start', props.exam)
  router.push(`/exams/${props.exam.id}/taking`)
}

const handleViewResult = () => {
  router.push(`/exams/${props.exam.id}/result`)
}

const handleViewDetails = () => {
  router.push(`/exams/${props.exam.id}`)
}

const handleFavorite = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  try {
    // 这里应该调用收藏/取消收藏 API
    if (isFavorited.value) {
      ElMessage.success('已取消收藏')
    } else {
      ElMessage.success('收藏成功')
    }
    emit('favorite', props.exam, !isFavorited.value)
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

const getStatusIcon = (status) => {
  const icons = {
    'upcoming': ClockIcon,
    'ongoing': Warning,
    'completed': CircleCheck,
    'expired': CircleClose,
    'in_progress': Warning
  }
  return icons[status] || ClockIcon
}

const getStatusText = (status) => {
  const texts = {
    'upcoming': '即将开始',
    'ongoing': '进行中',
    'completed': '已结束',
    'expired': '已过期',
    'in_progress': '答题中'
  }
  return texts[status] || status
}

const getDifficultyText = (difficulty) => {
  const texts = {
    'easy': '简单',
    'medium': '中等',
    'hard': '困难'
  }
  return texts[difficulty] || difficulty
}

const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

const getScoreStatus = (score) => {
  if (score >= 90) return '优秀'
  if (score >= 80) return '良好'
  if (score >= 60) return '及格'
  return '不及格'
}

const getScoreColor = (score) => {
  if (score >= 90) return '#67c23a'
  if (score >= 80) return '#409eff'
  if (score >= 60) return '#e6a23c'
  return '#f56c6c'
}

const formatRemainingTime = (time) => {
  // 这里应该格式化剩余时间
  return time
}
</script>

<style lang="scss" scoped>
.exam-card {
  background: var(--el-bg-color);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-light);
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
  
  &--clickable {
    cursor: pointer;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
      border-color: var(--el-color-primary-light-7);
    }
  }
  
  &--small {
    .exam-info {
      padding: 12px;
    }
    
    .exam-title {
      font-size: 14px;
    }
  }
  
  &--medium {
    .exam-info {
      padding: 16px;
    }
  }
  
  &--large {
    .exam-info {
      padding: 20px;
    }
    
    .exam-title {
      font-size: 18px;
    }
  }
  
  .exam-status {
    position: absolute;
    top: 0;
    right: 0;
    padding: 6px 12px;
    border-radius: 0 8px 0 8px;
    font-size: 12px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 4px;
    
    &.status-upcoming {
      background: var(--el-color-info-light-8);
      color: var(--el-color-info);
    }
    
    &.status-ongoing {
      background: var(--el-color-warning-light-8);
      color: var(--el-color-warning);
    }
    
    &.status-completed {
      background: var(--el-color-success-light-8);
      color: var(--el-color-success);
    }
    
    &.status-expired {
      background: var(--el-color-danger-light-8);
      color: var(--el-color-danger);
    }
    
    &.status-in_progress {
      background: var(--el-color-primary-light-8);
      color: var(--el-color-primary);
    }
  }
  
  .exam-info {
    padding: 16px;
    padding-top: 40px;
    
    .exam-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin: 0 0 8px 0;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }
    
    .exam-description {
      color: var(--el-text-color-regular);
      font-size: 13px;
      line-height: 1.5;
      margin: 0 0 12px 0;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }
    
    .exam-tags {
      display: flex;
      align-items: center;
      gap: 6px;
      margin-bottom: 12px;
      flex-wrap: wrap;
      
      .exam-tag {
        font-size: 11px;
        height: 20px;
        line-height: 18px;
      }
      
      .more-tags {
        color: var(--el-text-color-placeholder);
        font-size: 11px;
      }
    }
    
    .exam-stats {
      display: flex;
      align-items: center;
      gap: 16px;
      margin-bottom: 12px;
      flex-wrap: wrap;
      
      .stat-item {
        display: flex;
        align-items: center;
        gap: 4px;
        color: var(--el-text-color-regular);
        font-size: 12px;
        
        .el-icon {
          font-size: 14px;
        }
      }
    }
    
    .exam-time {
      margin-bottom: 12px;
      
      .time-item {
        display: flex;
        align-items: center;
        gap: 6px;
        color: var(--el-text-color-regular);
        font-size: 12px;
        margin-bottom: 4px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .el-icon {
          font-size: 14px;
        }
        
        .remaining-time {
          color: var(--el-color-warning);
          font-weight: 500;
        }
      }
    }
    
    .exam-score {
      margin-bottom: 12px;
      
      .score-info {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 6px;
        
        .score-label {
          color: var(--el-text-color-regular);
          font-size: 12px;
        }
        
        .score-value {
          font-size: 16px;
          font-weight: 600;
          
          &.score-excellent {
            color: var(--el-color-success);
          }
          
          &.score-good {
            color: var(--el-color-primary);
          }
          
          &.score-pass {
            color: var(--el-color-warning);
          }
          
          &.score-fail {
            color: var(--el-color-danger);
          }
        }
        
        .score-status {
          font-size: 12px;
          font-weight: 500;
        }
      }
    }
    
    .exam-progress {
      margin-bottom: 12px;
      
      .progress-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 6px;
        
        .progress-label {
          color: var(--el-text-color-regular);
          font-size: 12px;
        }
        
        .progress-value {
          color: var(--el-color-primary);
          font-size: 12px;
          font-weight: 600;
        }
      }
    }
    
    .exam-actions {
      display: flex;
      gap: 8px;
      align-items: center;
      flex-wrap: wrap;
      
      .el-button {
        flex: 1;
        min-width: 80px;
      }
      
      .favorite-btn {
        flex: none;
        width: 32px;
        height: 32px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .exam-card {
    .exam-info {
      padding: 12px;
      padding-top: 36px;
      
      .exam-title {
        font-size: 14px;
      }
      
      .exam-stats {
        gap: 12px;
      }
      
      .exam-actions {
        flex-direction: column;
        
        .el-button {
          width: 100%;
        }
        
        .favorite-btn {
          width: 32px;
          align-self: flex-end;
        }
      }
    }
  }
}

// 深色模式适配
@media (prefers-color-scheme: dark) {
  .exam-card {
    background: var(--el-bg-color);
    border-color: var(--el-border-color);
    
    &--clickable:hover {
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
      border-color: var(--el-color-primary-light-3);
    }
  }
}
</style>